package org.whuims.pois.action;

import com.google.gson.Gson;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.whuims.pois.dao.ClusterDao;
import org.whuims.pois.dao.DataDao;
import org.whuims.pois.model.Cluster;
import org.whuims.pois.model.DataC;
import org.whuims.poms.bean.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by 坤 on 2014/5/19 0019.
 */
public class PlaceAnalyzeAction extends DispatchAction {
    private ClusterDao clusterDao = new ClusterDao();

    public ActionForward getHeadMap(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {

        String clusterID = request.getParameter("clusterID");   //聚类ID

        long startTime = System.currentTimeMillis();

        long cluster = 0;
        try {
            cluster = Long.parseLong(clusterID);
        } catch (NumberFormatException e) {
            return mapping.findForward("success");
        }

        String location = locationData(cluster);

        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");

        request.setAttribute("loc", location);
        System.out.println("loc:" + location);
        return mapping.findForward("success");
    }

    private String locationData(long cluster) {
        List<DataC> list = getDataList(cluster);
        Map<String, Integer> map = getAddressMap(list);
        Map<BaiduLocation, Integer> map1 = new HashMap<BaiduLocation, Integer>();
        List<PointEntity> pointList = new ArrayList<PointEntity>();
        try {
            map1 = getListForLocation("json", "Gb8gFUKuPydZ5K3HC7Aw3VwV", map);
        } catch (IOException io) {

        }
        for (BaiduLocation baiduLocation : map1.keySet()) {

            ResultForBaiduMap result = baiduLocation.getResult();
            if (result != null) {
                Location location = result.getLocation();
                pointList.add(new PointEntity(location.getLng(), location.getLat(), (int) Math.random() * 300));
            }

        }
        for (int i = 0; i < pointList.size(); i++) {
            System.out.println("点的数量：" + pointList.get(i).getCount());
        }
        return new Gson().toJson(pointList);
    }

    private DataDao dataDao = new DataDao();

/*    output 默认：xml	json或xml	输出格式为json或者xml；
    ak	必须 	用户申请注册的key，自v2开始参数修改为“ak”，之前版本参数为“key”；
    sn	非必须  	若用户所用ak的校验方式为sn校验时该参数必须。 （sn生成算法）；（已去掉）
    callback 非必须 默认无	callback=showLocation(JavaScript函数名)	将json格式的返回值通过callback函数返回以实现jsonp功能；
    */

//    //得到测试数据(100条)
//    private List<DataC> getTestData() {
//        List<DataC> list = dataDao.select();
//        return list;
//    }


    private Map<BaiduLocation, Integer> getListForLocation(String output, String ak, Map<String, Integer> addressMap) throws IOException {
        long startTime = System.currentTimeMillis();
        Map<BaiduLocation, Integer> baiduMap = new HashMap<BaiduLocation, Integer>();
        List<String> urlList = new ArrayList<String>();
        HttpClient httpClient = new HttpClient();
        //创建GET方法的实例
        Set<String> addressSet = addressMap.keySet();
        for (String string : addressSet) {
            String address = null;
            try {
                address = URLEncoder.encode(string, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=" + output + "&ak=" + ak;
            System.out.println("请求的URL：" + url);
            GetMethod getMethod = new GetMethod(url);
            //使用系统提供的默认的恢复策略
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler());
            try {
                //执行getMethod
                int statusCode = httpClient.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method failed: "
                            + getMethod.getStatusLine());
                }
                //读取内容
                byte[] responseBody = getMethod.getResponseBody();
                //处理内容
                String urlPath = new String(responseBody);
                System.out.println("返回的内容：" + urlPath);
                //通过gson转成javaBean
                BaiduLocation bd = new Gson().fromJson(urlPath, BaiduLocation.class);
                System.out.println("请求状态：" + bd.getStatus());
                //返回正确的经纬度放入Map中
                if (bd.getStatus() == 0) baiduMap.put(bd, addressMap.get(string));
            } catch (HttpException e) {
                //发生致命的异常，可能是协议不对或者返回的内容有问题
                System.out.println("Please check your provided http address!");
                e.printStackTrace();
            } catch (IOException e) {
                //发生网络异常
                e.printStackTrace();
            } finally {
                //释放连接
                getMethod.releaseConnection();
            }
        }
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("取经纬度所用时间： " + (endTime - startTime) + "ms");
        return baiduMap;
    }

    //String 代表地址， Interger 代表次数
    public Map<String, Integer> getAddressMap(List<DataC> list) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (int i = 0; i < list.size(); i++) {
            EntityEntity entity = list.get(i).getEntity();
            if (entity != null) {
                List<String> listString = entity.getPlaces();
                if (listString.size() != 0) for (int j = 0; j < listString.size(); j++) {
                    if (map.containsKey(listString.get(j))) map.put(listString.get(j), map.get(listString.get(j)) + 1);
                    map.put(listString.get(j), 1);
                }
            }
        }
        for (java.util.Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) {
            Object obj = iterator.next();
            System.out.println(obj);// 循环输出key
            System.out.println("key=" + obj + " value=" + map.get(obj));
        }
        System.out.println("共有地址数量：" + map.size());
        return map;
    }

    public List<DataC> getDataList(Long clusterID) {
        List<DataC> listForDataC = new ArrayList<DataC>();
        Cluster cluster = (Cluster) clusterDao.get(clusterID);
        String simID = cluster.getSimilarid();
        String[] strings = null;
        if (simID.length() != 0) {
            strings = simID.split(",");
            System.out.println(strings.length);
            for (int i = 0; i < strings.length; i++) {
//                System.out.println("第" + i + "个：" + strings[i]);
                listForDataC.add(dataDao.get(Long.parseLong(strings[i])));
            }
        }
        return listForDataC;
    }


}
